package com.hs.srm.base.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.hs.srm.common.utils.DateUtils;
import com.hs.srm.common.utils.ToolUtil;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author Wangpeidong
 * @create 2018-06-07 22:12
 **/
public class DomesticUtils {

	/**
	 * 订单号计数器
	 */
	private static Integer orderNoCount = 0;

	private final static Integer MAX_ORDER_NO_COUNT = 9999;

	/**
	 * 获取订单计数器
	 * @return
	 */
	private static synchronized String getCount() {
		if(DomesticUtils.orderNoCount >= DomesticUtils.MAX_ORDER_NO_COUNT) {
			DomesticUtils.orderNoCount = 1;
		} else {
			DomesticUtils.orderNoCount++;
		}
		return DomesticUtils.highPositionZero(String.valueOf(DomesticUtils.orderNoCount), 4);
	}

	public static String List2Str(List<Long> list) {
		String result = "";
		if(!ObjectUtils.isEmpty(list)) {
			for(int i = 0; i < list.size(); i++) {
				if(i == 0) {
					result += String.valueOf(list.get(i));
				} else {
					result += ("," + String.valueOf(list.get(i)));
				}
			}
		}
		return result;
	}

	public static List<Long> Str2List(String str) {
		List<Long> result = new ArrayList<>();
		if(StrUtil.isNotBlank(str)) {
			String[] arr = str.split(",");
			if(!ObjectUtils.isEmpty(arr)) {
				for(String item : arr) {
					if(StrUtil.isNotBlank(item)) {
						result.add(Long.valueOf(item));
					}
				}
			}
		}
		return result;
	}

	/**
	 * 生成订单号（订单类型标志+yyyyMMddHHmmss+4位计数器）
	 * @param type 订单类型
	 * @param userId 操作人ID
	 * @return
	 */
	public static String generateOrderNo(Integer type, Long userId) {
		String head = "";
		String orderNo = "";
		if(DomesticConst.OrderTypeEnum.CLEANUP.getValue().equals(type)) {
			head = "BJ";
		} else if(DomesticConst.OrderTypeEnum.HOUSEKEEP.getValue().equals(type)) {
			head = "JZ";
		} else if(DomesticConst.OrderTypeEnum.PACKAGECARD.getValue().equals(type)) {
			head = "TC";
		} else if(DomesticConst.OrderTypeEnum.INSURANCE.getValue().equals(type)) {
			head = "BX";
		} else if(DomesticConst.OrderTypeEnum.EMPLOYER_QUALITY.getValue().equals(type)) {
			head = "EB";
		} else if(DomesticConst.OrderTypeEnum.AUNT_QUALITY.getValue().equals(type)) {
			head = "AB";
		} else if(DomesticConst.OrderTypeEnum.HOUSEKEEP_SERVICE.getValue().equals(type)) {
			head = "SO";
		}
		String time = DateUtil.format(new Date(), "yyMMddHHmmss");
		orderNo = head + time + DomesticUtils.getCount();
		return orderNo;
	}

	/**
	 * 高位补零
	 * @param val 待处理的字符
	 * @param totalNum 总共的位数
	 * @return
	 */
	private static String highPositionZero(String val, int totalNum) {
		String temp = "";
		if(val.length() < totalNum) {
			for(int i = 1; i <= (totalNum - val.length()); i++) {
				temp += "0";
			}
		}
		return temp + val;
	}

	public static String getFileUploadPath(String fileUploadPath) {
		// 如果没有写文件上传路径,保存到临时目录
		if(ObjectUtils.isEmpty(fileUploadPath)) {
			return ToolUtil.getTempPath();
		}
		// 判断有没有结尾符,没有得加上
		if(!fileUploadPath.endsWith(File.separator)) {
			fileUploadPath = fileUploadPath + File.separator;
		}
		// 加上当前日期
		String date = DateUtils.format(new Date(), DateUtils.DATE_PATTERN);
		String fileSavePath = fileUploadPath + date + File.separator;
		// 判断目录存不存在,不存在得加上
		File file = new File(fileSavePath);
		if(!file.exists() && !file.isDirectory()) {
			file.mkdirs();
		}
		return fileSavePath;
	}

	public static String getFileUrl(String fileName, String rootPath) {
		String[] arr = fileName.split("\\.");
		String suffix = ".jpg";
		if(arr.length == 2) {
			suffix = "." + arr[1];
		}
		String pictureName = UUID.randomUUID().toString() + suffix;
		String path = DomesticUtils.getFileUploadPath(rootPath);
		// 判断有没有结尾符,没有得加上
		if(!path.endsWith(File.separator)) {
			path = path + File.separator;
		}
		return path + pictureName;
	}

	/**
	 * 生成并下载二维码
	 * @param url 二维码对于URL
	 * @param width 二维码宽
	 * @param height 二维码高
	 * @param format  二维码格式
	 * @return
	 * @throws WriterException
	 * @throws IOException
	 */
	public static ResponseEntity<byte[]> getResponseEntity(String url, int width, int height, String format)
			throws WriterException, IOException {
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		// 生成矩阵
		BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
		// 将矩阵转为Image
		BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		// 将BufferedImage转成out输出流
		ImageIO.write(image, format, out);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		return new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.CREATED);
	}
}
